package jdbc_code;


import util.jdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 事务操作
 */
public class jdbcDemo8 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstat1 = null;
        PreparedStatement pstat2 = null;
        try {
            //1.获取连接
            conn = jdbcUtils.getConnection();
            //开启事务
            conn.setAutoCommit(false);
            //2.定义sql
            //2.1张三 - 500
            String sql1 = "update account set balance = balance - ? where id = ?";
            //2.2李四 + 500
            String sql2 = "update account set balance = balance + ? where id = ?";
            //3.获取执行sql对象
            pstat1 = conn.prepareStatement(sql1);
            pstat2 = conn.prepareStatement(sql2);
            //5.设置参数
            pstat1.setDouble(1,500);
            pstat1.setInt(2,1);

            pstat2.setDouble(1,500);
            pstat2.setInt(2,2);
            //6.执行sql
            pstat1.executeUpdate();

            //手动制造异常
            int i = 3/0;
            pstat2.executeUpdate();

            conn.commit();
        } catch (Exception e) {
            //事务回滚
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            jdbcUtils.close(pstat1,conn);
            jdbcUtils.close(pstat2,null);
        }
    }
}
